%%% @doc
%%%выдает идентификаторы
%%% @end
-module(id_manager).
-include("definitions.hrl").
%% API
-export([init/0, get_next_id/0, start/0, stop/0]).

-define(TABLE_ID_PATH, "ebin/tableForId.txt").

stop() ->
  case whereis(manager) of
    undefined -> ok;
    Pid -> Pid ! {id_man_stop, self()},
      receive
        id_man_stopped ->
          io:format("id_manager finished~n")
      end
  end,
  ok.

get_next_id() ->
  manager ! {next, self()},
  receive
    {nextIdFromMan, Id} when is_integer(Id)
      -> Id
  end.

start() ->
  register(manager, spawn(id_manager, init, [])).

read_table_file() ->
  {ok, IsDebug} = application:get_env(debug),
  case IsDebug of
    true ->
      {ok, Tab} = dets:open_file(tableForId, [{type, set}, {file, ?TABLE_ID_PATH},
        {auto_save, infinity}, {ram_file, true}, {keypos, #key_id_dts.key}]),
      dets:delete_all_objects(Tab),
      Tab;
    false ->
      {ok, Tab} = dets:open_file(?TABLE_ID_PATH),
      Tab
  end.

init() ->
  Table = read_table_file(),
  Previous =
    case dets:lookup(Table, ?KEY_FOR_LAST_RECORD)
    of
      [X] -> X;
      [] -> #key_id_dts{}
    end,
  StartIndex = Previous#key_id_dts.value,
  loop_event(StartIndex, Table)
.

loop_event(CurrentIndex, FileTable) ->
  receive
    {next, From} -> From ! {nextIdFromMan, CurrentIndex + 1},
      loop_event(CurrentIndex + 1, FileTable);
    {id_man_stop, Pid} ->
      %положить в файл
      LastId = #key_id_dts{key = ?KEY_FOR_LAST_RECORD, value = CurrentIndex + 1},
      dets:insert(FileTable, LastId),
      dets:close(FileTable),
      Pid ! id_man_stopped
  end.